import * as types from "@/common/vuex.const";
import _ from "lodash";
import {uuid} from 'vue-uuid';

let lifeData = {};
try {
    // 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
    const res = uni.getStorageSync(types.LIFE_DATA);
    if (!_.isEmpty(res)) {
        lifeData = JSON.parse(res);
        console.log(lifeData)
    }
    //不存在设备号就预先生成一个
    if (!lifeData[types.DEVICE_NUMBER_KEY]) {
        lifeData[types.DEVICE_NUMBER_KEY] = uuid.v4();
    }
    uni.setStorageSync(types.LIFE_DATA, JSON.stringify(lifeData));
} catch (e) {
    console.log(e)
}

export default {
    namespaced: true,
    state: {
        vuex_user: lifeData[types.USER_KEY] ? lifeData[types.USER_KEY] : {},
        vuex_token: lifeData[types.TOKEN_KEY] ? lifeData[types.TOKEN_KEY] : "",
        vuex_seq: lifeData[types.MSG_SEQ_KEY] ? lifeData[types.MSG_SEQ_KEY] : 1,
        vuex_device_number: lifeData[types.DEVICE_NUMBER_KEY],
        vuex_routing_key: "",
    },
    mutations: {
        [types.UPDATE_ROUTING_KEY]: (state, routingKey) => {
            state.vuex_routing_key = routingKey;
        },
        [types.UPDATE_TOKEN]: (state, token) => {
            state.vuex_token = token;
            lifeData[types.TOKEN_KEY] = token;
            uni.setStorageSync(types.LIFE_DATA, JSON.stringify(lifeData));
        },
        [types.UPDATE_USER]: (state, user) => {
            state.vuex_user = user;
            lifeData[types.USER_KEY] = user;
            uni.setStorageSync(types.LIFE_DATA, JSON.stringify(lifeData));
        },
        [types.INC_SEQ]: (state) => {
            state.vuex_seq = state.vuex_seq + 1;
            lifeData[types.MSG_SEQ_KEY] = state.vuex_seq;
            uni.setStorageSync(types.LIFE_DATA, JSON.stringify(lifeData));
        },
        [types.CLEAR_LOGIN_INFO]: (state) => {
            state.vuex_user = {};
            state.vuex_token = null;
            lifeData[types.USER_KEY] = state.vuex_user;
            lifeData[types.TOKEN_KEY] = state.vuex_token;
            uni.setStorageSync(types.LIFE_DATA, JSON.stringify(lifeData));
        }
    },
    getters: {}
};
